package com.mxw.account.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.mxw.account.mapper.AccountRepository;
import com.mxw.account.mapper.domain.AccountEntity;
import com.mxw.account.dto.AccountDTO;
import com.mxw.commons.restful.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @Description TODO
 * @Author RingKo
 * @Date 2022/1/17 17:23
 * @Version 1.0
 */
@Slf4j
@Controller
public class ExcelTestController {
  @Autowired
  private AccountRepository accountRepository;

  /**
   * 导出
   */
  @GetMapping("/account/downLoadExcel/{batchNumber}")
  public Result<Void> downLoadExcel(@PathVariable String batchNumber, HttpServletResponse response) {
    log.info("batchNumber:{}",batchNumber);
    List<AccountEntity> list = accountRepository.findAll();
    List<AccountDTO> accountDTOS = BeanUtil.copyToList(list, AccountDTO.class);
    Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), AccountDTO.class, accountDTOS);
    Sheet sheetAt = workbook.getSheetAt(0);
    int physicalNumberOfCells = sheetAt.getRow(0).getPhysicalNumberOfCells();
    Row row = sheetAt.getRow(1);
    for (int i = 0; i < physicalNumberOfCells; i++) {
      Cell cell = row.getCell(i);
      CellStyle cellStyle = workbook.createCellStyle();
      cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
      if (i < 2) {
        cellStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
      } else {
        cellStyle.setFillForegroundColor(IndexedColors.LIGHT_ORANGE.getIndex());
      }
      cell.setCellStyle(cellStyle);
    }

    try {
      response.setCharacterEncoding("UTF-8");
      response.setHeader("content-Type", "application/vnd.ms-excel");
      response.setHeader(
          "Content-Disposition",
          "attachment;filename=" + URLEncoder.encode("111 222 333" + ".xlsx", "UTF-8"));

      workbook.write(response.getOutputStream());
    } catch (IOException e) {
      e.printStackTrace();
    }
    return Result.respond();
  }

  /**
   * @Description: 按模板导出
   */
  @GetMapping("/account/repayment/download2/{batchNumber}")
  public Result<Void> downLoadExcel2(@PathVariable String batchNumber, HttpServletResponse response) {
    // 数据列表
    List<AccountDTO> dataList = new ArrayList<>();
    List sumList = new ArrayList<>();
    dataList.add(AccountDTO.builder().amount(null).build());
    dataList.add(AccountDTO.builder().amount(BigDecimal.valueOf(200)).build());
    dataList.add(AccountDTO.builder().amount(BigDecimal.valueOf(300)).build());
    dataList.add(AccountDTO.builder().amount(BigDecimal.valueOf(400)).build());
    dataList.add(AccountDTO.builder().amount(BigDecimal.valueOf(500)).build());
    BigDecimal sumA = dataList.stream()
        .map(AccountDTO::getAmount)
        .filter(Objects::nonNull)
        .reduce(BigDecimal.ZERO, BigDecimal::add);
    Map map = new HashMap();
    map.put("sumA", sumA);
    map.put("sumB", 2000);
    sumList.add(map);
    Map<String, Object> dataMap = new HashMap<>();
    dataMap.put("list", dataList);
    dataMap.put("sumList", sumList);
    TemplateExportParams params = new TemplateExportParams();
    params.setHeadingRows(1);
    params.setHeadingStartRow(0);
    params.setTempParams("t");
    params.setSheetNum(new Integer[] {0});
    String templatePath = "static/Invoice-Repayment-Template.xlsx";
    params.setTemplateUrl(templatePath);
    Workbook workbook = ExcelExportUtil.exportExcel(params, dataMap);
    String fileName =
        batchNumber
            + "-repayment-"
            + cn.hutool.core.date.DateUtil.format(
            DateUtil.date(), DatePattern.PURE_DATETIME_PATTERN);
    try {
      response.setCharacterEncoding("UTF-8");
      response.setContentType("application/vnd.ms-excel");
      response.setHeader(
          "Content-Disposition",
          "attachment; filename="
              + new String(fileName.getBytes("gb2312"), StandardCharsets.ISO_8859_1)
              + ".xls");
      workbook.write(response.getOutputStream());
    } catch (Exception e) {
      e.printStackTrace();
    }
    return Result.respond();
  }

//  /**
//   *导入
//   */
//  @RequestMapping("/importXls")
//  @ResponseBody
//  public void importSS(@RequestParam("file") MultipartFile file) {
//    List<DongBei> iotCollectionPoints = null;
//    int filed = 0;
//    int success = 0;
//    try {
//      iotCollectionPoints = ExcelUtils.importExcel(file, DongBei.class);
//      IotCollPointIsMain coll = new IotCollPointIsMain();
//      for (DongBei pointIsMain : iotCollectionPoints) {
//        try {
//          coll.setMinValues("0");
//          coll.setMaxValues("10000");
//          coll.setCreateTime(date);
//          coll.setId(UniqueIdUtil.genId());
//          coll.setCreateUser(userId);
//          coll.setIsDelete("0");
//          coll.setIsReadOnly("110");
//          coll.setStatus("0");
//          //Tag名称
//          coll.setKeyName(pointIsMain.getKeyName());
//          coll.setName(pointIsMain.getKeyName());
//          coll.setCreatetime(date);
//          coll.setCreateBy(userId);
//          iotCollPointIsMainService.saveColl(coll);
//          success++;
//        } catch (Exception e) {
//          filed++;
//          logger.error(e.getMessage(), e.fillInStackTrace());
//        }
//      }
//      System.out.println("成功导入数据：" + success + "条 , 失败" + filed + "条");
//    } catch (Exception e) {
//      logger.error(e.getMessage(), e.fillInStackTrace());
//    }
}
